// dh-doctor_schedules 云对象 - 医生排班管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete, getUserById, getUserList } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-doctor_schedules] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-doctor_schedules] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);

		const writeMethods = ['create', 'update', 'delete', 'batch'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
	 * 根据ID查询排班（包含关联的医生姓名和医院名称）
	 */
	async getScheduleById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '排班ID不能为空');
			}

			const res = await db.collection('dh-doctor_schedules').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '排班不存在');
			}
			
		const schedule = res.data[0];
		
		// 检查是否已软删除
		if (schedule.is_deleted === true) {
			return formatResponse(404, null, '排班不存在');
		}
		let doctorHospitalId = null;
		
		// 获取医生姓名和医生所属医院ID
		if (schedule.doctor_id) {
			try {
				const doctorRes = await db.collection('dh-doctors').doc(schedule.doctor_id).field({
					user_id: true,
					hospital_id: true
				}).get();
				
				if (doctorRes.data.length > 0) {
					const doctor = doctorRes.data[0];
					
					// 保存医生的医院ID，以备后用
					if (doctor.hospital_id) {
						doctorHospitalId = typeof doctor.hospital_id === 'object' ? doctor.hospital_id._id : doctor.hospital_id;
					}
					
					// 获取医生真实姓名（使用统一的用户查询工具）
					if (doctor.user_id) {
						const userInfo = await getUserById(doctor.user_id, 'default', false, true);
						if (userInfo) {
							schedule.doctor_name = userInfo.realName || userInfo.displayName || '未知医生';
						}
					}
				}
			} catch (err) {
				console.error('获取医生信息失败:', err);
				schedule.doctor_name = '未知医生';
			}
		}
		
		// 获取医院名称（优先使用排班的hospital_id，否则使用医生的hospital_id）
		const hospitalIdToUse = schedule.hospital_id || doctorHospitalId;
		if (hospitalIdToUse) {
			try {
				const hospitalRes = await db.collection('dh-hospitals').doc(hospitalIdToUse).field({
					hospital_name: true
				}).get();
				
				if (hospitalRes.data.length > 0) {
					schedule.hospital_name = hospitalRes.data[0].hospital_name || '暂无';
				} else {
					schedule.hospital_name = '暂无';
				}
			} catch (err) {
				console.error('获取医院信息失败:', err);
				schedule.hospital_name = '暂无';
			}
		} else {
			schedule.hospital_name = '暂无';
		}
			
			return formatResponse(200, schedule);
		} catch (error) {
			return formatError(error, '获取排班失败');
		}
	},

	/**
	 * 获取排班列表（包含关联的医生姓名和医院名称）
	 */
	async listSchedules(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
		skip = parseInt(skip) || 0;
		limit = parseInt(limit) || 20;
		
		// 默认不显示已删除记录
		query.is_deleted = false;
		
		const res = await db.collection('dh-doctor_schedules')
			.where(query)
			.skip(skip)
				.limit(limit)
				.orderBy('schedule_date', 'desc')
				.get();
			
			// 获取总数
			const countRes = await db.collection('dh-doctor_schedules').where(query).count();
			const total = countRes.total;
			
		// 为每条排班记录添加医生姓名和医院名称
		const schedules = await Promise.all(res.data.map(async (schedule) => {
			let doctorHospitalId = null;
			
			// 获取医生姓名和医生所属医院ID
			if (schedule.doctor_id) {
				try {
					const doctorRes = await db.collection('dh-doctors').doc(schedule.doctor_id).field({
						user_id: true,
						hospital_id: true
					}).get();
					
					if (doctorRes.data.length > 0) {
						const doctor = doctorRes.data[0];
						
						// 保存医生的医院ID
						if (doctor.hospital_id) {
							doctorHospitalId = typeof doctor.hospital_id === 'object' ? doctor.hospital_id._id : doctor.hospital_id;
						}
						
						// 获取医生真实姓名（使用统一的用户查询工具）
						if (doctor.user_id) {
							const userInfo = await getUserById(doctor.user_id, 'default', false, true);
							if (userInfo) {
								schedule.doctor_name = userInfo.realName || userInfo.displayName || '暂无';
							}
						}
					}
				} catch (err) {
					console.error('获取医生信息失败:', err);
					schedule.doctor_name = '暂无';
				}
			}
			
			// 获取医院名称（优先使用排班的hospital_id，否则使用医生的hospital_id）
			const hospitalIdToUse = schedule.hospital_id || doctorHospitalId;
			if (hospitalIdToUse) {
				try {
					const hospitalRes = await db.collection('dh-hospitals').doc(hospitalIdToUse).field({
						hospital_name: true
					}).get();
					
					if (hospitalRes.data.length > 0) {
						schedule.hospital_name = hospitalRes.data[0].hospital_name || '暂无';
					} else {
						schedule.hospital_name = '暂无';
					}
				} catch (err) {
					console.error('获取医院信息失败:', err);
					schedule.hospital_name = '暂无';
				}
			} else {
				schedule.hospital_name = '暂无';
			}
			
			return schedule;
		}));
			
			return formatResponse(200, schedules, 'success', { count: total });
		} catch (error) {
			return formatError(error, '获取排班列表失败');
		}
	},

	/**
	 * 创建排班
	 */
	async createSchedule(data) {
		try {
			if (!data.doctor_id || !data.schedule_date) {
				return formatResponse(400, null, '医生ID和排班日期不能为空');
			}

			let scheduleData = {
				doctor_id: data.doctor_id,
				schedule_date: data.schedule_date,
				start_time: data.start_time || '08:00',
				end_time: data.end_time || '18:00',
				slot_duration_minutes: data.slot_duration_minutes || 30,
				total_slots: data.total_slots || 10,
				booked_slots: data.booked_slots || 0,
				available_slots: data.available_slots || data.total_slots || 10,
				status: data.status !== undefined ? data.status : 1,
				remark: data.remark || '',
				is_deleted: false,  // 软删除字段，默认未删除
				create_time: Date.now(),
				update_time: Date.now()
			};

			// 🏥 自动挂载医院ID（单一医院系统特性）
			scheduleData = await autoMountHospitalId(scheduleData);

			const res = await db.collection('dh-doctor_schedules').add(scheduleData);
			return formatResponse(201, { _id: res.id }, '排班创建成功');
		} catch (error) {
			return formatError(error, '创建排班失败');
		}
	},

	/**
	 * 更新排班信息
	 */
	async updateSchedule(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '排班ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			await db.collection('dh-doctor_schedules').doc(id).update(updateData);
			return formatResponse(200, null, '排班信息更新成功');
		} catch (error) {
			return formatError(error, '更新排班失败');
		}
	},

	/**
	 * 删除排班
	 */
	async deleteSchedule(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '排班ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-doctor_schedules', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '排班已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除排班失败');
		}
	},

	/**
	 * 批量更新排班
	 */
	async batchUpdateSchedules(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			const promises = updates.map(item =>
				db.collection('dh-doctor_schedules').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	/**
	 * 批量删除排班
	 */
	async batchDeleteSchedules(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-doctor_schedules', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	},

	/**
	 * 获取医生指定日期的排班
	 */
	async getDoctorScheduleByDate(doctorId, scheduleDate) {
		try {
			if (!doctorId || !scheduleDate) {
				return formatResponse(400, null, '医生ID和排班日期不能为空');
			}

			const res = await db.collection('dh-doctor_schedules')
				.where({ 
					doctor_id: doctorId, 
					schedule_date: scheduleDate,
					is_deleted: false
				})
				.get();

			return formatResponse(200, res.data.length > 0 ? res.data[0] : null);
		} catch (error) {
			return formatError(error, '获取医生排班失败');
		}
	},

	/**
	 * 减少可用时段数
	 */
	async decreaseAvailableSlots(id, count = 1) {
		try {
			if (!id) {
				return formatResponse(400, null, '排班ID不能为空');
			}

			await db.collection('dh-doctor_schedules').doc(id).update({
				available_slots: _.inc(-count),
				update_time: Date.now()
			});

			return formatResponse(200, null, '可用时段已更新');
		} catch (error) {
			return formatError(error, '更新可用时段失败');
		}
	},

	/**
	 * 获取医生列表（用于下拉选择）
	 */
	async getDoctorList() {
		try {
			const doctorRes = await db.collection('dh-doctors').field({
				_id: true,
				user_id: true
			}).get();
			
			// 为每个医生获取真实姓名（使用统一的用户查询工具）
			// 先收集所有医生user_id，批量查询
			const doctorUserIds = doctorRes.data.map(d => d.user_id).filter(Boolean);
			let doctorNameMap = {};
			
			if (doctorUserIds.length > 0) {
				// 使用 getUserList 批量查询医生信息
				const allDoctors = await getUserList({
					includeRoles: ['doctor'],
					format: 'default',
					limit: 1000,
					decryptSensitiveInfo: true
				});
				
				// 构建用户ID到姓名的映射
				allDoctors.forEach(user => {
					if (doctorUserIds.includes(user._id)) {
						doctorNameMap[user._id] = user.realName || user.displayName || '未知医生';
					}
				});
			}
			
			// 构建医生列表
			const doctors = doctorRes.data.map(doctor => {
				const doctorName = doctor.user_id ? (doctorNameMap[doctor.user_id] || '未知医生') : '未知医生';
				return {
					value: doctor._id,
					label: doctorName
				};
			});
			
			return formatResponse(200, doctors);
		} catch (error) {
			return formatError(error, '获取医生列表失败');
		}
	},

	/**
	 * 获取医院列表（用于下拉选择）
	 */
	async getHospitalList() {
		try {
			const hospitalRes = await db.collection('dh-hospitals').field({
				_id: true,
				hospital_name: true
			}).get();
			
			const hospitals = hospitalRes.data.map(hospital => ({
				value: hospital._id,
				label: hospital.hospital_name || '未知医院'
			}));
			
			return formatResponse(200, hospitals);
		} catch (error) {
			return formatError(error, '获取医院列表失败');
		}
	}
};
